<!--
  @author:  long
  @date:    2023/4/4
  @file:    绩效查询
  @require:
-->
<template>
  <div class="evaluationList">
    <FixedOperation>
      <div class="flex items-center relative justify-center">
        <div class="absolute left-0">
          <i class="i-ion-ios-paper mr-1 text-lx"></i>
          <span class="text-lg font-semibold">绩效考评</span>
        </div>
        <!-- 内容 -->
        <div class="flex items-center">
          <div
            @click="switchType('self')"
            :class="['tab-item', isActive == 'self' ? 'isActive' : '']"
          >
            自评
          </div>
          <div
            v-if="props.assessor"
            @click="switchType('other')"
            :class="['tab-item', isActive == 'other' ? 'isActive' : '']"
          >
            他评
          </div>
        </div>
      </div>
    </FixedOperation>
    <div class="app-container">
      <el-row :gutter="10" class="mb-3" v-if="isActive == 'other'">
        <el-col :span="4" v-if="displayMode == '1'">
          <!--    考核部门      -->
          <el-tree-select
            v-model="queryForm.deptId"
            node-key="deptId"
            clearable
            :data="deptData"
            :props="deptProps"
            :render-after-expand="false"
            placeholder="考核部门"
            filterable
          />
        </el-col>

        <el-col :span="4">
          <el-select
            v-model="queryForm.userId"
            placeholder="请选择人员"
            @focus="userInputFocus"
            class="w-full"
            clearable
          >
            <el-option
              v-for="(item, index) in selectOptionObj['userId']"
              :key="index"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="queryForm.status"
            placeholder="状态"
            class="w-full"
            clearable
          >
            <el-option
              v-for="(item, index) in statusOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button icon="Search" type="primary" @click="handleQuery"
            >查询
          </el-button>
          <el-button icon="RefreshLeft" @click="handleEmpty">重置</el-button>
        </el-col>
      </el-row>

      <el-row class="mb-5" v-if="isActive == 'other'">
        <el-col :span="6">
          <!--   内容主体   -->
          <el-radio-group v-model="tableType" v-loading="radioLoading">
            <el-radio-button
              v-for="(item, index) in displayModeOptions"
              :key="index"
              :label="item.tableType"
              @change="switchMode(item)"
              >{{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-col>
      </el-row>
      <!--    按人考评    -->
      <div v-if="tableType == 'person'">
        <el-table
          ref="tableRef"
          :data="tableData"
          border
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="55"
          />
          <el-table-column label="部门" prop="appraiseeDeptName">
          </el-table-column>
          <el-table-column label="姓名" prop="appraiseeName"></el-table-column>
          <el-table-column label="状态" prop="assessStatus">
            <template #default="scope">
              <dict-tag
                :options="assess_status"
                :value="scope.row.assessStatus"
              ></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="待评指标数" prop="indsIncompleted">
          </el-table-column>
          <el-table-column label="已评指标数" prop="indsCompleted">
          </el-table-column>
          <el-table-column label="考核频率">
            <template #default="scope">
              <div v-if="scope.row.assessStatus == '1'">
                <el-tooltip placement="top">
                  <template #content>
                    <div style="width: 380px">
                      <el-row>
                        <el-col :span="6" class="text-center">考核频次</el-col>
                        <el-col :span="9" class="text-center"
                          >考评日期起
                        </el-col>
                        <el-col :span="9" class="text-center"
                          >考评日期止
                        </el-col>
                      </el-row>
                      <el-row
                        v-for="(item, index) in scope.row.assessTimeItems"
                        :key="index"
                      >
                        <el-col :span="6" class="text-center"
                          >{{ item.assessFrequency }}
                        </el-col>
                        <el-col :span="9" class="text-center"
                          >{{ item.assessStime }}
                        </el-col>
                        <el-col :span="9" class="text-center"
                          >{{ item.assessEtime }}
                        </el-col>
                      </el-row>
                    </div>
                  </template>
                  <el-button link type="primary"> 查看</el-button>
                </el-tooltip>
              </div>
              <div v-else>
                <dict-tag
                  :options="examine_frequency"
                  :value="scope.row.assessFrequency"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="考评起始时间"
            prop="assessStime"
            width="160"
            border
            align="center"
          >
            <template #default="scope">
              <div v-if="scope.row.assessStatus == '1'">
                <el-tooltip placement="top">
                  <template #content>
                    <div style="width: 380px">
                      <el-row>
                        <el-col :span="6" class="text-center">考核频次</el-col>
                        <el-col :span="9" class="text-center"
                          >考评日期起
                        </el-col>
                        <el-col :span="9" class="text-center"
                          >考评日期止
                        </el-col>
                      </el-row>
                      <el-row
                        v-for="(item, index) in scope.row.assessTimeItems"
                        :key="index"
                      >
                        <el-col :span="6" class="text-center"
                          >{{ item.assessFrequency }}
                        </el-col>
                        <el-col :span="9" class="text-center"
                          >{{ item.assessStime }}
                        </el-col>
                        <el-col :span="9" class="text-center"
                          >{{ item.assessEtime }}
                        </el-col>
                      </el-row>
                    </div>
                  </template>
                  <el-button link type="primary"> 查看</el-button>
                </el-tooltip>
              </div>
              <div v-else>{{ scope.row.assessStime }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="考评结束时间"
            width="160"
            prop="assessEtime"
            align="center"
          >
            <template #default="scope">
              <div v-if="scope.row.assessStatus == '1'">
                <el-tooltip placement="top">
                  <template #content>
                    <div style="width: 380px">
                      <el-row>
                        <el-col :span="6" class="text-center">考核频次</el-col>
                        <el-col :span="9" class="text-center"
                          >考评日期起
                        </el-col>
                        <el-col :span="9" class="text-center"
                          >考评日期止
                        </el-col>
                      </el-row>
                      <el-row
                        v-for="(item, index) in scope.row.assessTimeItems"
                        :key="index"
                      >
                        <el-col :span="6" class="text-center"
                          >{{ item.assessFrequency }}
                        </el-col>
                        <el-col :span="9" class="text-center"
                          >{{ item.assessStime }}
                        </el-col>
                        <el-col :span="9" class="text-center"
                          >{{ item.assessEtime }}
                        </el-col>
                      </el-row>
                    </div>
                  </template>
                  <el-button link type="primary"> 查看</el-button>
                </el-tooltip>
              </div>
              <div v-else>{{ scope.row.assessEtime }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                type="success"
                size="small"
                :disabled="scope.row.assessStatus == '2'"
                @click="toScoreHandle(scope.row)"
                >考评
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--    按指标考评    -->
      <div v-if="tableType == 'target'">
        <el-table
          ref="tableRef"
          :data="tableData"
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="55" />
          <el-table-column label="一级指标" prop="firstLevel">
          </el-table-column>
          <el-table-column label="二级指标" prop="secondLevel">
          </el-table-column>
          <el-table-column label="指标说明" prop="content" width="250">
          </el-table-column>
          <el-table-column label="分值权重" prop="score"></el-table-column>
          <el-table-column
            label="被考核人"
            prop="appraiseeName"
          ></el-table-column>
          <el-table-column label="状态" prop="assessStatus" width="120">
            <template #default="scope">
              <dict-tag
                :options="assess_status"
                :value="scope.row.assessStatus"
              ></dict-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="考评开始时间"
            width="160"
            prop="assessStime"
          ></el-table-column>
          <el-table-column
            label="考评结束时间"
            width="160"
            prop="assessEtime"
          ></el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                type="success"
                size="small"
                :disabled="scope.row.assessStatus == '2'"
                @click="toScoreHandle(scope.row)"
                >考评
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        @pagination="getList"
      />
    </div>
    <SelectDialog :dialog-param="dialogParam" @ok="selectData"></SelectDialog>
  </div>
</template>

<script setup name="Evaluation List">
import { getCurrentInstance } from 'vue'
import useCommonStore from '@/store/modules/common'
import {
  getAssessListByIndicators,
  getAssessListByPerson,
  getSelfAssessList
} from '@/api/officeManage/appraisal'
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance()
// 通用数据store
const commonStore = useCommonStore()
const userStore = useUserStore()
const props = defineProps({
  type: {
    type: String,
    default: 'self'
  },
  mode: {
    type: String,
    default: ''
  },
  assessor: {
    type: Boolean,
    default: false
  }
})
// 选中的tab
const isActive = ref('self')
const data = reactive({
  tableData: [],
  tableType: 'person',
  loading: false,
  displayModeOptions: [
    {
      label: '按人考评',
      value: '1',
      tableType: 'person'
    },
    {
      label: '按指标考评',
      value: '2',
      tableType: 'target'
    }
  ],
  queryForm: {
    pageNum: 1,
    pageSize: 10,
    deptId: '',
    userId: '',
    status: ''
  },
  deptProps: { label: 'deptName' },
  deptData: [],
  statusOptions: [
    { label: '全部', value: '' },
    { label: '正在考评期', value: '1' },
    { label: '已过考评期', value: '2' }
  ],
  total: 0,
  dialogParam: {}, //弹窗组件配置
  selectOptionObj: {} // select
})
const {
  total,
  displayModeOptions,
  deptData,
  queryForm,
  deptProps,
  monthNames,
  levelOptions,
  dialogParam,
  selectOptionObj,
  tableType,
  tableData,
  statusOptions,
  loading
} = toRefs(data)

const emit = defineEmits(['switchModule'])
const radioLoading = ref(false)
const { assess_status, examine_frequency } = proxy.useDict(
  'assess_status',
  'examine_frequency'
)
/**
 * 切换类型
 * @param type
 */
const switchType = async type => {
  if (type == 'self') {
    tableType.value = 'person'
  }
  isActive.value = type

  getList()
}

/**
 * 跳转到考评
 */
const toScoreHandle = row => {
  if (isActive.value == 'self') {
    emit('switchModule', 'scoreTable', 'self', row)
  } else {
    switch (tableType.value) {
      case 'person':
        emit('switchModule', 'scoreTable', 'other', row)
        break
      case 'target':
        emit('switchModule', 'indicator', '', row)
        break
    }
  }
}

/**
 * 查询
 */
function handleQuery() {
  queryForm.value.pageNum = 1
  getList()
}

/**
 * 重置
 */
async function handleEmpty() {
  queryForm.value = {
    pageNum: 1,
    pageSize: 10,
    deptId: '',
    userId: '',
    status: ''
  }
  await getList()
}

/**
 * 查询
 */
const getList = () => {
  loading.value = true
  switch (isActive.value) {
    //   自评
    case 'self':
      getSelfAssessListApi()
      break
    //   他评
    case 'other':
      switch (tableType.value) {
        case 'person':
          getAssessListByPersonApi()
          break
        case 'target':
          getAssessListByIndicatorsApi()
          break
      }
      break
  }
}

/**
 * 获取考评列表-按指标
 */
const getAssessListByIndicatorsApi = () => {
  let params = {
    assessStatus: queryForm.value.status,
    deptId: queryForm.value.deptId,
    pageNum: queryForm.value.pageNum,
    pageSize: queryForm.value.pageSize,
    userId: queryForm.value.userId
  }
  getAssessListByIndicators(params)
    .then(res => {
      if (res.code === 200) {
        tableData.value = res.data.records
        total.value = res.data.total
      }
    })
    .finally(() => {
      loading.value = false
      radioLoading.value = false
    })
}

/**
 * 获取考评列表-按人考评
 */
const getAssessListByPersonApi = () => {
  let params = {
    assessStatus: queryForm.value.status,
    deptId: queryForm.value.deptId,
    pageNum: queryForm.value.pageNum,
    pageSize: queryForm.value.pageSize,
    userId: queryForm.value.userId
  }
  getAssessListByPerson(params)
    .then(res => {
      if (res.code === 200) {
        tableData.value = res.data.records

        total.value = res.data.total
      }
    })
    .finally(() => {
      loading.value = false
      radioLoading.value = false
    })
}

/**
 * 获取考评列表-自评
 */
const getSelfAssessListApi = () => {
  let params = {
    pageNum: queryForm.value.pageNum,
    pageSize: queryForm.value.pageSize,
    userId: userStore.user.userId
  }
  getSelfAssessList(params)
    .then(res => {
      if (res.code === 200) {
        tableData.value = res.data.records
        total.value = res.data.total
      }
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 切换显示模式
 * @param mode
 */
const switchMode = mode => {
  tableType.value = mode.tableType
  tableData.value = []
  loading.value = true
  radioLoading.value = true
  switch (mode.tableType) {
    case 'person':
      getAssessListByPersonApi()
      break
    case 'target':
      getAssessListByIndicatorsApi()
      break
  }
}

/**
 * 弹窗选取获取选中的值
 * @param val
 *  type 业务类型
 *     selectData 选中的数据[{value: 1, label: '王晓易', $treeNodeId: 2}]
 *     labelData 选中的数据label ['王晓易']
 *     defaultCheckedKeys 选中的数据id [1]
 *     dialogVisible: false 弹出框的关闭
 */
function selectData(val) {
  console.info('val', val)
  //归属人员
  if (val.type == 'userId') {
    if (!val.selectData.length) {
      queryForm.value[val.type] = ''
    } else {
      selectOptionObj.value[val.type] = val.selectData
      queryForm.value[val.type] = val.defaultCheckedKeys[0]
    }
  }
}

/**
 * 归属人员input获取焦点事件
 */
const userInputFocus = () => {
  dialogParam.value.type = 'userId'
  dialogParam.value.title = '选择归属人员'
  dialogParam.value.dataType = 'person'
  dialogParam.value.multiple = false
  dialogParam.value.checkStrictly = false
  dialogParam.value.nodeKey = 'id'
  selectOptionObj.value['userId'] = []

  // 有默认值
  if (queryForm.value['userId'] && queryForm.value['userId'].length) {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = [queryForm.value['userId']]
  } else {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = []
  }
}

/**
 * 获取部门数据查询
 */
const getDeptData = async () => {
  const deptRes = await commonStore.getDeptTreeData()
  // deptRes.forEach(item => {
  //   item.disabled = item.deptType === '1' ? true : false
  // })
  deptData.value = proxy.handleTree(deptRes, 'deptId')
}

/**
 * 初始化查询
 */
const init = () => {
  isActive.value = proxy.type
  if (proxy.mode) {
    tableType.value = proxy.mode
  }
  // 获取部门数据
  getDeptData()
  getList()
}
init()
</script>

<style scoped lang="scss">
.i-ion-ios-paper {
  color: var(--el-color-primary);
}

.tab-item {
  @apply text-gray-500 px-5 py-1 cursor-pointer text-base mx-2 font-semibold;
}

.isActive {
  @apply rounded-full border-1 border-blue-500 border-solid text-blue-500;
}

:deep(.monthPopper) {
  width: 300px !important;
}

.monthPopper .el-select-dropdown__item {
  width: 25%;
  display: inline-block;
  box-sizing: border-box;
  text-align: center;
  padding: 0;
}
</style>
